package com.hb.gp.impl;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import com.hb.gp.GPInsCommand;
import com.hb.gp.GPType;
import com.hb.gp.IGPCommandMessageService;

public class BaseGPCommand {
	protected static Map<GPInsCommand, Class<?>> map = null;

	private static void test() {
		map = new HashMap<GPInsCommand, Class<?>>();
		Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
		classes.add(GPDelete.class);
		classes.add(GPExternalauthEnticate.class);
		classes.add(GPInitializeUpdate.class);
		classes.add(GPInstall.class);
		classes.add(GPPutKey.class);
		classes.add(GPSelect.class);
		classes.add(GPSetStatus.class);
		classes.add(GPLoad.class);
		classes.add(GPStore.class);
		classes.add(GP52.class);
		for (Class<?> cla : classes) {
			Annotation[] anno = cla.getAnnotations();
			for (Annotation no : anno) {
				if (no instanceof GPType) {
					GPType gp = (GPType) no;
					String type = gp.INS().toString();
					System.out.println("class " + cla.getSimpleName()
							+ " is the gp command " + type);
					map.put(gp.INS(), cla);
					break;
				}
			}
		}
	}

	public static IGPCommandMessageService getInstance(String apduCommandMessage) {
		try {
			IGPCommandMessageService igp = null;
			if (map == null) {
				System.out.println(" init  the apdu command message impl");
				test();
			}
			String ins = apduCommandMessage.replaceAll(" ", "").substring(2, 4)
					.toUpperCase();
			String type = GPInsCommand.INS_.toString() + ins.toUpperCase();
			try {
				GPInsCommand gpEnum = Enum.valueOf(GPInsCommand.class, type);
				Class<?> o = map.get(gpEnum);
				igp = (IGPCommandMessageService) o.newInstance();
			} catch (Exception e) {
				// TODO: handle exception
				// throw e;
				igp = GPDefault.class.newInstance();
			}
			return igp;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}
	}
}
